package com.lishem.nettymain.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class MyClientChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /***
     * 获取响应数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("来自服务端的数据:"+msg.toString(CharsetUtil.UTF_8));
    }

    /***
     * 向服务端发送数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //ByteBuf->数据需要手动清理、手动释放，否则会积压到内存中，最终会引发内存溢出
        ctx.writeAndFlush(Unpooled.copiedBuffer("beijing!".getBytes(CharsetUtil.UTF_8)));
    }

    /***
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
